package com.cong.security.browser;

import com.cong.security.core.constant.SecurityConstant;
import com.cong.security.core.properties.SecurityProperties;
import com.cong.security.core.support.SimpleResponse;
import com.cong.security.core.support.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
public class BrowserSecurityController {

    /*请求缓存*/
    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 当需要身份证认证时，跳转到当前接口
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(SecurityConstant.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)// 返回状态码401
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // 拿到引发跳转的请求
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            // 引发跳转请求的url
            String target = savedRequest.getRedirectUrl();
            log.info("引发跳转请求的url是:[{}]", target);
            // 以.html结尾，直接跳转到登录页上
            if (StringUtils.endsWith(target, ".html")) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }
        // 不是html请求，返回401状态码，提示语无所谓
        return new SimpleResponse("用户未登录或权限不足");
    }

    @RequestMapping("social/user")
    public SocialUser getSocialUserInfo(HttpServletRequest request) {
        SocialUser socialUser = new SocialUser();
        Connection connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        socialUser.setProviderId(connection.getKey().getProviderId());
        socialUser.setProviderUserId(connection.getKey().getProviderUserId());
        socialUser.setNickName(connection.getDisplayName());
        socialUser.setHead(connection.getImageUrl());
        return socialUser;
    }
}
